package com.krtech.wecard.module.ramble.controller;

import cn.dev33.satoken.SaManager;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.krtech.wecard.framework.exception.BusinessException;
import com.krtech.wecard.framework.model.CommRes;
import com.krtech.wecard.framework.security.Inner;
import com.krtech.wecard.module.ramble.entity.RambleHexiaoPeople;
import com.krtech.wecard.module.ramble.service.RambleHexiaoPeopleService;
import com.krtech.wecard.module.sys.entity.SysKeyValue;
import com.krtech.wecard.module.sys.enums.SysEnums;
import com.krtech.wecard.module.sys.pojo.PublicSignitureVo;
import com.krtech.wecard.module.sys.pojo.WxAuth;
import com.krtech.wecard.module.sys.service.LoginService;
import com.krtech.wecard.module.sys.service.SysKeyValueService;
import com.krtech.wecard.utils.WxBizDecryptUtils;
import com.krtech.wecard.utils.sms.SmsUtil;
import com.krtech.wecard.utils.verify.VerifyCode;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.security.NoSuchAlgorithmException;

@RestController
@RequestMapping("/rambleUtil")
@Slf4j
@Api(tags = "佳得乐漫步-工具类")
public class RambleUtil {

    @Autowired
    private SysKeyValueService keyValueService;

    @Autowired
    private RambleHexiaoPeopleService hexiaoPeopleService;

    @Autowired
    private LoginService loginService;

    /**
     * 时间有效时间
     */
    private static final Integer CODE_EXPIRED = 1;

    @GetMapping("/getVerificationCode")
    @ApiOperation(value = "获得验证码")
    @Inner(value = false)
    public CommRes getVerificationCode(String phone) throws Exception {

        String currentVerification = SaManager.getSaTokenDao().get("getVerificationCode:"+phone);
        if (StrUtil.isNotEmpty(currentVerification)){
            throw new BusinessException("一分钟只能获取一次验证码，请勿频繁点击");
        }

        //生成随机6位数二维码
        String verification = RandomUtil.randomNumbers(6);

        VerifyCode verifyCode = new VerifyCode();
        verifyCode.setCode(verification);
        //拼接验证码
        verifyCode.setPhone(phone);
        verifyCode.setTime(CODE_EXPIRED.toString());
        SmsUtil.sendSms(verifyCode);

        //存入redis,并且限制过期时间，并且设置唯一键setNx，保证一个手机一分钟只能发送一次短信验证
        SaManager.getSaTokenDao().set("getVerificationCode:"+phone,verification,CODE_EXPIRED * 60);

        return CommRes.ok(verification);
    }

    @GetMapping("/getPubliSigniture")
    @ApiOperation(value = "获得公众号签名")
    @Inner(value = false)
    public PublicSignitureVo getPubliSigniture(String url) throws NoSuchAlgorithmException {
        if (StrUtil.isEmpty(url)){
            return loginService.getPubliSigniture();
        }
        return loginService.getPubliSigniture(url);
    }

    @GetMapping("/verifyPhone")
    @ApiOperation(value = "手机验证码登陆")
    @Inner(value = false)
    public boolean getByShifuCode(String verifiCode,String phone){
        if (StrUtil.isEmpty(phone)){
            throw new BusinessException("必填参数手机号码不能不为空");
        }

        if (StrUtil.isEmpty(verifiCode)){
            throw new BusinessException("必填参数验证码不能不为空");
        }

        //判断验证码
        boolean judgeVerificationCode = SmsUtil.judgeVerificationCode(phone, verifiCode);
        if (!judgeVerificationCode){
            throw new BusinessException("验证码不正确，请检查");
        }

        //判断当前人员是否是核销人员
        int count = hexiaoPeopleService.count(new QueryWrapper<RambleHexiaoPeople>().eq(RambleHexiaoPeople.COL_PHONE, phone));

        if (count <= 0){
            throw new BusinessException("您不是核销人员，不能登陆核销页面");
        }

        return true;
    }

    @PostMapping("/decrypt")
    @ApiOperation(value = "微信解密")
    public CommRes decrypt(@RequestBody WxAuth wxAuth) {

        //获得appid和secret
        SysKeyValue appId = keyValueService.getOne(new QueryWrapper<SysKeyValue>()
                .eq(SysKeyValue.COL_SYS_NAME, SysEnums.WX_APPLETS_APPID));
        SysKeyValue secret = keyValueService.getOne(new QueryWrapper<SysKeyValue>()
                .eq(SysKeyValue.COL_SYS_NAME, SysEnums.WX_APPLETS_SECRET));

        //构造hutool请求
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid="+appId.getSysValue()+
                "&secret="+secret.getSysValue()+"&js_code="+ wxAuth.getCode() +"&grant_type=authorization_code";

        String resultStr = HttpUtil.get(url);
        log.info("步数解密result:"+resultStr);

        JSONObject jsonObject = JSONUtil.parseObj(resultStr);
        Object openidObj = jsonObject.get("openid");

        log.info("当前用户的openid:"+openidObj);
        Object sessionKeyObj = jsonObject.get("session_key");
        if (sessionKeyObj == null){
            throw new BusinessException("获得sessionKey异常");
        }
        String sessionKey = String.valueOf(sessionKeyObj);

        wxAuth.setSessionKey(sessionKey);

        String wxDecrypt = WxBizDecryptUtils.wxDecrypt(wxAuth.getEncryptedData(), wxAuth.getSessionKey(), wxAuth.getIv());
        log.info("wxDecrypt解密结果:"+wxDecrypt);
        return CommRes.ok(wxDecrypt);
    }
}
